package com.stanford.ml.svm;

/**
 * A utility class that holds some analytical methods
 * required by the SVM classifier
 * 
 * @author Fatih Sunor
 */
public class SVMUtil {

	/**
	 * Calculates the inner product of two vectors
	 * @param x1 the first vector
	 * @param x2 the second vector
	 * @return The dot product of the vectors
	 */
	private static double innerProduct(Feature [] x1, Feature [] x2) {
		double sum=0;
		int i,j;
		for (i=0,j=0;x1!=null && x2!=null && i<x1.length && j<x2.length;) {
			if (x1[i].getIndex()<x2[j].getIndex()) {
				i++;
			}
			else if (x2[j].getIndex()<x1[i].getIndex()) {
				j++;
			}
			else {
				sum+=x1[i].getValue()*x2[j].getValue();
				i++;
				j++;
			}
		}
		return sum;
	}
	
	/**
	 * Linear kernel: k(x1,x2) = <x1,x2>
	 * @param x1 first vector
	 * @param x2 second vector
	 * @return linear kernel value
	 */
	public static double linearKernel(Feature[] x1, Feature[] x2) {
		return innerProduct(x1, x2);
	}
}